package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class AdminManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private AdminService adminService;

    // 获取验证码
    public LineCaptcha genVerification(String uuid) {
        // 制作验证码
        LineCaptcha lineCaptcha = new LineCaptcha(300, 150);
        // 获取随机数
        String code = lineCaptcha.getCode();
        // 存储到redis中
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE + uuid, code, Duration.ofMinutes(5));
        return lineCaptcha;
    }

    // 用户登录
    public ResponseEntity adminLogin(String username, String password, String verificationCode, String uuid) {
        // 1.获取redis中验证码
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        // 2.对比验证码是否一致
        if (!StrUtil.equals(verificationCode, codeFromRedis)) {
            throw new BusinessException("验证码错误~~~");
        }
        // 3.根据用户名查询
        Admin admin = adminService.findByUsername(username);
        if (admin == null) {
            throw new BusinessException("用户名不存在~~~");
        }
        // 4.对比密码是否一致
        // 4-1 对用户输入的密码进行加密
        String md5Pwd = SecureUtil.md5(password);
        // 4-2 跟数据对比
        if (!StrUtil.equals(md5Pwd, admin.getPassword())) {
            throw new BusinessException("密码错误~~~");
        }
        // 5. 登录成功
        // 5-1 干掉验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + uuid);
        // 5-2 制作token
        admin.setPassword(null);
        Map<String, Object> calims = BeanUtil.beanToMap(admin);
        String token = JwtUtil.createToken(calims);
        // 6.向redis中存储token
        String json = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));
        // 7.返回token
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("token", token);
        return ResponseEntity.ok(resultMap);
    }

    // 根据token解析admin
    public Admin findAdminByToken(String token) {
        Admin admin = null;
        // 1.根据token获取reids中数据
        // 1-1 前端工程师有一个习惯在传递token时会加一个参数 【Bearer token】
        token = token.replaceAll("Bearer ", "");
        // 1-2查询redis
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
        // 1-3 非空判断
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        // 2.json转换admin
        admin = JSON.parseObject(json, Admin.class);
        // 3.完成续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));

        // 4.返回结果
        return admin;
    }

    // admin登出
    public void adminLogout(String token) {
        // 1. 前端工程师有一个习惯在传递token时会加一个参数 【Bearer token】
        token = token.replaceAll("Bearer ", "");
        // 2.从reids中移除
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
    }
}
